<template>
  <div>
    <!-- 新增 -->
    <a-modal
      :width="600"
      :visible="visible"
      :confirm-loading="loading"
      :forceRender="true"
      :maskClosable="false"
      :title="isUpdate ? '修改' : '新建'"
      :body-style="{ paddingBottom: '8px' }"
      @update:visible="updateVisible"
      @ok="save"
      @close="updateVisible(false)"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ md: { span: 5 }, sm: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }"
      >
        <!-- <a-form-item label="最后一层:" name="type">
          <a-select v-model:value="form.type">
            <a-select-option value="N">否</a-select-option>
            <a-select-option value="Y">是</a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="父级:" name="parentNo">
          <a-tree-select
            v-if="!isUpdate"
            v-model:value="form.parentNo"
            style="width: 100%"
            :tree-data="orgList"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择上级机构"
            :fieldNames="{
              children: 'children',
              label: 'name',
              key: 'tagStyleNo',
              value: 'tagStyleNo',
            }"
            allow-clear
            tree-default-expand-all
          />
          <a-tree-select
            v-else
            ref="treeSelectRef"
            :disabled="form.parentNo === '-1'"
            v-model:value="form.parentNo"
            style="width: 100%"
            :tree-data="orgList"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择上级机构"
            :fieldNames="{
              children: 'children',
              label: 'name',
              key: 'tagStyleNo',
              value: 'tagStyleNo',
            }"
            allow-clear
            tree-default-expand-all
            :key="treeSelectKey"
            @change="handleSelectChange"
          />
        </a-form-item>
        <a-form-item label="风格:" name="style">
          <a-input
            v-model:value="form.style"
            placeholder="请输入风格"
            allow-clear
            @input="handleInput"
            autocomplete="off"
            :maxlength="32"
          />
        </a-form-item>

        <!-- <a-form-item label="新旧:" name="newFlagChecked">
          <a-switch
            checked-children="是"
            un-checked-children="否"
            v-model:checked="newFlagChecked"
          />
        </a-form-item> -->

        <!-- <a-form-item label="热门:" name="hotFlagChecked">
          <a-switch
            checked-children="是"
            un-checked-children="否"
            v-model:checked="hotFlagChecked"
          />
        </a-form-item> -->

        <!-- <a-form-item label="图片上传:">
          <a-upload
            :action="uploadUrl"
            :multiple="true"
            :file-list="fileList"
            name="file"
            :data="extraData"
            @change="handleUploadChange"
          >
              <a-button>
                <upload-outlined></upload-outlined>
                上传
              </a-button>
          </a-upload>
        </a-form-item> -->

        <a-form-item label="图片上传:" name="imageFileId" v-if="!isUpdate">
          <a-upload
            name="file"
            :multiple="true"
            :action="FileUploadUrlToDb"
            :headers="headers"
            :before-upload="beforeUpload"
            v-model:file-list="fileList"
            @change="afterUpload"
            :showUploadList="showUploadList"
          >
            <a-button>
              <template #icon>
                <CloudUploadOutlined />
              </template>
              <span>上传</span>
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue/es';
import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import useFormData from '/@/utils/common/use-form-data';
import { useUserStore } from '/@/store/modules/user';
import { TagStyleInfoApi } from '/@/api/touch/tagStyle/TagStyleInfoApi';
import { TagStyleInfoRequest } from '/@/api/touch/tagStyle/model/TagStyleInfoModel';
import { FileApi, FileUploadUrl } from '/@/api/system/operation/FileApi';
import Unauthorized from 'ant-design-vue/lib/result/unauthorized';

const emit = defineEmits<{
  (e: 'done'): void;
  (e: 'update:visible', value: boolean): void;
}>();

const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 是否是修改
  isUpdate: false;
  // 修改回显的数据
  data?: Object;
  // 组织机构列表
  orgList: Array<{ id: string; name: string; children?: Array<any> }>;
}>();
// 组织列表
const orgLists = ref(props.orgList);

// 强制刷新组件的 key
const treeSelectKey = ref(0);
// 表单实例
const formRef = ref<FormInstance | null>(null);
// 提交状态
const loading = ref<boolean>(false);
// newFlag check
const newFlagChecked = ref<boolean>(false);
const hotFlagChecked = ref<boolean>(false);
const fileList = ref([]);

const showUploadList = ref<boolean>(false);

// 表单数据
let { form, resetFormFields } = useFormData<TagStyleInfoRequest>({
  imageFileId: undefined,
  style: undefined,
  newFlag: undefined,
  hotFlag: undefined,
  parentNo: undefined,
});

// 表单验证规则
const rules = reactive({
  style: [{ required: true, message: '请输入风格', type: 'string', trigger: 'change' }],
  // imageFileId: [{ required: true, message: '请上传文件', type: 'string', trigger: 'change' }],
  parentNo: [{ required: true, message: '请输入父级', type: 'string', trigger: 'change' }],
});

watch(
  () => props.visible,
  () => {
    if (!props.visible) {
      resetFormFields();
      formRef.value?.clearValidate();
      fileList.value = [];
    } else {
      if (Object.keys(props.data || {}).length === 0) {
        resetFormFields();
        formRef.value?.clearValidate();
        fileList.value = [];
      } else {
        form = Object.assign({}, props.data);
        console.log('form', form);
        showUploadList.value = true;
      }
    }
  },
);

// 根据 isNew 切换表单数据

// 上传文件的url（上传到数据库）
const FileUploadUrlToDb = ref<string>(
  `${import.meta.env.VITE_GLOB_API_URL}${FileUploadUrl}?secretFlag=N&fileLocation=5`,
);

const userStore = useUserStore();
const token = computed(() => {
  return userStore.getToken;
});
const headers = reactive({
  Authorization: token.value,
});

/**
 * 控制上传到数据库的图片不能超过1M
 *
 * @author fengshuonan
 * @date 2021/4/12 22:29
 */
const beforeUpload = (file: any) => {
  const isLt2M = file.size / 1024 / 1024 <= 2;
  if (!isLt2M) {
    message.error('上传图片不能超过2MB');
  }
  return isLt2M;
};

/**
 * 上传成功的回调
 *
 * @author fengshuonan
 * @date 2021/4/2 17:03
 */
const afterUpload = ({ file }) => {
  showUploadList.value = true;
  loading.value = true;
  if (file.response) {
    message.success('上传成功');
    loading.value = false;
    form.imageFileId = file.response.data.fileId;
  }
};
const treeSelectRef = ref(null);
const handleSelectChange = (value: string, label, node) => {
  console.log('value', value, node, label);
  treeSelectKey.value++;
};
// token
const handleInput = (event) => {
  console.log('event', event);
  const maxLength = 32;
  if (event.target.value.length > maxLength) {
    form.style = event.target.value = event.target.value.slice(0, maxLength);
  }
};
/**
 * 保存编辑
 *
 */
const save = () => {
  // 校验表单
  if (!formRef.value) {
    return;
  }
  formRef.value.validate().then((valid) => {
    if (valid) {
      // if (newFlagChecked.value === true) {
      //   form.newFlag = 'Y';
      // } else {
      //   form.newFlag = 'N';
      // }
      // if (hotFlagChecked.value === true) {
      //   form.hotFlag = 'Y';
      // } else {
      //   form.hotFlag = 'N';
      // }

      // // 获取已上传图片的fileId
      // form.imageFileId = imageFileId.value;
      // 修改加载框为正在加载
      loading.value = true;
      // 执行新增保存
      if (props.isUpdate) {
        TagStyleInfoApi.edit(form).then((result) => {
          // 移除加载框
          loading.value = false;
          // 提示添加成功
          message.success(result.message);
          // 关闭弹框，通过控制visible的值，传递给父组件
          updateVisible(false);
          // 触发父组件done事件
          emit('done');
          // 重置表单字段
          resetFormFields();
          formRef.value?.clearValidate();
          formRef.value?.resetFields();
          showUploadList.value = false; // 清空已上传的文件列表
          // form = {};

          // form = {
          //   imageFileId: undefined,
          //   style: undefined,
          //   newFlag: undefined,
          //   hotFlag: undefined,
          // };
          // 重置表单数据和状态
        });
      } else {
        console.log('formadd', form);
        TagStyleInfoApi.add(form)
          .then((result) => {
            // 移除加载框
            loading.value = false;
            // 提示添加成功
            message.success(result.message);
            // 关闭弹框，通过控制visible的值，传递给父组件
            updateVisible(false);
            // 触发父组件done事件
            emit('done');
            // 重置表单字段
            resetFormFields();
            formRef.value?.clearValidate();
            formRef.value?.resetFields();

            showUploadList.value = false; // 清空已上传的文件列表
            // 重置表单数据和状态
          })
          .catch(() => {
            loading.value = false;
          });
      }
    }
  });
};

/**
 * 更新编辑菜单界面的弹框是否显示
 *
 * @param value true-显示，false-隐藏
 * @author jiawei
 * @date 2021/4/7 12:00
 */

const updateVisible = (value: boolean) => {
  emit('update:visible', value);
  resetFormFields();
  formRef.value?.clearValidate();
  showUploadList.value = false;

  Object.keys(form).forEach((key) => {
    form[key] = undefined;
  });
};
</script>
